package com.codeoss.framework.webide.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Query;
import com.codeoss.framework.data.metadata.Restrictions;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.db.util.ValueNamePairUtil;
import com.codeoss.framework.impexp.ExportManager;
import com.codeoss.framework.util.ValueNamePair;
import com.codeoss.framework.view.component.store.IComponentStore;
import com.codeoss.framework.webide.request.DevFormDesignerRequest;
import com.codeoss.framework.webide.response.DevFormDesignerResponse;
import com.codeoss.framework.webide.service.IDevFormDesignerService;
import com.codeoss.module.ir.model.IrPage;
import com.codeoss.module.ir.service.IIrPageService;

@Service
public class DevFormDesignerService  implements IDevFormDesignerService {
    @Autowired
    private IIrPageService irPageService;
    @Autowired
    private IComponentStore componentStore;
    @Autowired
    private ITableStore tableStore;
    @Autowired
    private ExportManager exportManager;
    @Autowired
	private ValueNamePairUtil valueNamePairUtil;
	@Override
	public DevFormDesignerResponse init(String pageCode) {
		// TODO Auto-generated method stub
		DevFormDesignerResponse devFormDesignerResponse=new DevFormDesignerResponse();
		YunContext yunContext=YunContext.getCurrentContext();
		QueryWrapper<IrPage> irPageQuery=new QueryWrapper<IrPage>();
		irPageQuery.eq("page_code", pageCode);
		IrPage irPage=irPageService.getOne(irPageQuery);
		devFormDesignerResponse.setPageCode(irPage.getPageCode());
		devFormDesignerResponse.setName(irPage.getName());
		devFormDesignerResponse.setComponentModelJson(irPage.getComponentModelJson());
		devFormDesignerResponse.setComponentTreeModelJson(irPage.getComponentTreeModelJson());
		devFormDesignerResponse.setCurrentComponentId(irPage.getCurrentComponentId());
		
		Table modelTable=tableStore.get("ir_model");
		List<ValueNamePair> tableList = valueNamePairUtil.getValueNamePairList(yunContext, modelTable, null, false, true);
		devFormDesignerResponse.setTableList(tableList);
		return devFormDesignerResponse;
	}
	
	@Override
	@Transactional
	public DevFormDesignerResponse dataSave(DevFormDesignerRequest request) {
		// TODO Auto-generated method stub
		DevFormDesignerResponse devFormDesignerResponse=new DevFormDesignerResponse();
		QueryWrapper<IrPage> irPageQuery=new QueryWrapper<IrPage>();
		irPageQuery.eq("page_code", request.getPageCode());
		IrPage irPage=irPageService.getOne(irPageQuery);
		irPage.setName(request.getPageTitle());
		irPage.setComponentModelJson(request.getComponentModelJson());
		irPage.setComponentTreeModelJson(request.getComponentTreeModelJson());
		irPage.setCurrentComponentId(request.getCurrentComponentId());
		irPageService.update(irPage);
		
		componentStore.remove(request.getPageCode());
		return devFormDesignerResponse;
	}

	@Override
	public DevFormDesignerResponse dataExport(String pageCode) throws IOException {
		// TODO Auto-generated method stub
		DevFormDesignerResponse devFormDesignerResponse=new DevFormDesignerResponse();
		YunContext yunContext=YunContext.getCurrentContext();
		Table table=tableStore.get("ir_page");
		Query query=new Query();
		query.add(Restrictions.eq("page_code", pageCode));
		ByteArrayOutputStream os=new ByteArrayOutputStream(); 
		exportManager.exportProperties(yunContext, table, query, os);
		String fileContent=new String(os.toByteArray(),"utf-8");
		String fileName="page_"+pageCode+".prop";
		devFormDesignerResponse.setFileContent(fileContent);
		devFormDesignerResponse.setFileName(fileName);
		return devFormDesignerResponse;
	}

	@Override
	public DevFormDesignerResponse initColumnConfig(String tableName, boolean editable) {
		// TODO Auto-generated method stub
		DevFormDesignerResponse devFormDesignerResponse=new DevFormDesignerResponse();
		Table table=tableStore.get(tableName);
		devFormDesignerResponse.setTreeTable(table.isTreeTable());
		List<Column> columnList=table.getAllColumnList();
		List<Map<String,Object>> mapList=new ArrayList<Map<String,Object>>();
		devFormDesignerResponse.setColumnConfigList(mapList);
		if(!editable) {
			for(int i=0;i<columnList.size();i++) {
				Column column=columnList.get(i);
				Map<String,Object> map=new HashMap<String,Object>();
				mapList.add(map);
				map.put("columnName", column.getColumnName());
				map.put("name", column.getName());
				if(column.getDataType().equals("boolean")) {
					map.put("viewType","switch");
				}else {
					map.put("viewType","label");
				}
			}
		}else {
			for(int i=0;i<columnList.size();i++) {
				Column column=columnList.get(i);
				Map<String,Object> map=new HashMap<String,Object>();
				mapList.add(map);
				map.put("columnName", column.getColumnName());
				map.put("name", column.getName());
				String dataType = column.getDataType();
				String viewType = "text";
				if ("string".equals(dataType)) {
					viewType = "text";
				} else if ("long".equals(dataType) || "bigdecimal".equals(dataType) || "integer".equals(dataType)) {
					viewType = "number";
				} else if ("datetime".equals(dataType)) {
					viewType = "datetime";
				} else if ("date".equals(dataType)) {
					viewType = "date";
				} else if ("time".equals(dataType)) {
					viewType = "time";
				} else if ("boolean".equals(dataType)) {
					viewType = "checkbox";
				}
				if (column.getLookupInfo() != null) {
					viewType = "select";
				}
				if(column.isPrimaryKey()) {
					viewType = "label";
				}
				map.put("viewType",viewType);
			}
		}
		return devFormDesignerResponse;
	}

	@Override
	public DevFormDesignerResponse getChartConfig(String tableName) {
		// TODO Auto-generated method stub
		DevFormDesignerResponse devFormDesignerResponse=new DevFormDesignerResponse();
		Table table=tableStore.get(tableName);
		List<Column> columnList=table.getAllColumnList();
		List<ValueNamePair> fieldList=new ArrayList<ValueNamePair>();
		devFormDesignerResponse.setFieldList(fieldList);
		for(int i=0;i<columnList.size();i++) {
			Column column=columnList.get(i);
			ValueNamePair fieldPair=new ValueNamePair(column.getName()+"("+column.getColumnName()+")",column.getColumnName());
			fieldList.add(fieldPair);
		}
		return devFormDesignerResponse;
	}
	
}
